using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace StructureMap.WcfIntegration.Tests.Behaviours
{
    public class UnitOfWorkMessageInspector : IDispatchMessageInspector
    {
        private readonly IContainer container;

        public UnitOfWorkMessageInspector(IContainer container)
        {
            this.container = container;
        }

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            var unitOfWork = container.GetInstance<IUnitOfWork>();

            Debug.WriteLine("Before invoke");
            unitOfWork.Initialize();

            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            var unitOfWork = container.GetInstance<IUnitOfWork>();

            Debug.WriteLine("After invoke");
            unitOfWork.Commit();
            unitOfWork.Dispose();
        }
    }
}